package com.myapp.mobilesafe.activity;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.myapp.mobilesafe.entity.AppInfo;
import com.myapp.mobilesafe.utils.AppInfoUtils;

import java.util.ArrayList;

public class AppManagerActivity extends AppCompatActivity implements View.OnClickListener {
    private ListView lvApp;
    private AppInfoAdapter aiaa;
    private AppInfo mCurrentAppInfo;
    private ArrayList<AppInfo> list;
    private ScaleAnimation scaleAnimation;
    private LinearLayout llLoading;
    private ArrayList<AppInfo> mUserList;
    private ArrayList<AppInfo> mSystemList;
    private TextView tvHeader;
    private PopupWindow mPopupWindow;
    private View mPopupView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_manager);
        lvApp = (ListView) findViewById(R.id.lv_list);
        llLoading = (LinearLayout) findViewById(R.id.ll_loading);
        TextView tvSD = (TextView) findViewById(R.id.tv_sdcard_avail);
        TextView tvRom = (TextView) findViewById(R.id.tv_rom_avail);
        String sdSize = getAvailSpace(Environment.getExternalStorageDirectory().getAbsolutePath());
        String romSize = getAvailSpace(Environment.getDataDirectory().getAbsolutePath());
        tvSD.setText("sdcard可用:" + sdSize);
        tvRom.setText("内部存储可用:" + romSize);
        initAppData();
        tvHeader = (TextView) findViewById(R.id.tv_header);
        lvApp.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                if (mUserList != null && mSystemList != null) {
                    if (firstVisibleItem <= mUserList.size()) {
                        tvHeader.setText("用户应用(" + mUserList.size() + ")");
                    } else {
                        tvHeader.setText("系统应用(" + mSystemList.size() + ")");
                    }
                }
            }
        });
        lvApp.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                AppInfo info = aiaa.getItem(position);
                if(info!=null){
                    mCurrentAppInfo = info;
                    showPopupWindow(view);
                }

            }
        });

    }

    private void showPopupWindow(View view) {
        if(mPopupView==null){
            mPopupView = View.inflate(this, R.layout.popup_item_appinfo, null);
            mPopupWindow = new PopupWindow(mPopupView,
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
            TextView tvUninstall = (TextView) mPopupView
                    .findViewById(R.id.tv_uninstall);
            TextView tvLaunch = (TextView) mPopupView
                    .findViewById(R.id.tv_launch);
            TextView tvShare = (TextView) mPopupView
                    .findViewById(R.id.tv_share);
            tvUninstall.setOnClickListener(this);
            tvLaunch.setOnClickListener(this);
            tvShare.setOnClickListener(this);
            mPopupWindow.setBackgroundDrawable(new ColorDrawable());
            scaleAnimation = new ScaleAnimation(0,1,0,1,
                    Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,1);
            scaleAnimation.setDuration(500);
        }
        mPopupWindow.showAsDropDown(view, 60, -2 * view.getHeight());
        mPopupView.startAnimation(scaleAnimation);
    }

    private void initAppData() {
        llLoading.setVisibility(View.VISIBLE);
        new Thread(){
            @Override
            public void run() {
                list = AppInfoUtils.getInstalledApps(getApplicationContext());
                mUserList = new ArrayList<AppInfo>();
                mSystemList = new ArrayList<AppInfo>();
                for (AppInfo info : list) {
                    if (info.isUser) {
                        mUserList.add(info);
                    } else {
                        mSystemList.add(info);
                    }
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                         aiaa = new AppInfoAdapter();
                        lvApp.setAdapter(aiaa);
                        llLoading.setVisibility(View.GONE);
                    }
                });
            }
        }.start();
    }

    private String getAvailSpace(String path){
        StatFs statFs = new StatFs(path);
        long availBlocks = statFs.getAvailableBlocks();
        long blockSize = statFs.getBlockSize();
        long availSize = availBlocks * blockSize;
        String size = Formatter.formatFileSize(this,availSize);
        Log.i("hahah","@@@@！！"+size);
        return size;
    }
    class AppInfoAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mUserList.size() + mSystemList.size() + 2;// 增加两个标题栏
        }

        @Override
        public AppInfo getItem(int position) {
            if (position == 0 || position == mUserList.size() + 1) {
                // 碰到标题栏了
                return null;
            }
            if (position < mUserList.size() + 1) {
                return mUserList.get(position - 1);// 减掉1个标题栏
            } else {
                return mSystemList.get(position - mUserList.size() - 2);// 减掉两个标题栏
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        @Override
        public int getItemViewType(int position) {
            if (position == 0 || position == mUserList.size() + 1) {
                // 碰到标题栏了
                return 0;// 标题栏类型
            } else {
                return 1;// 普通类型
            }
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
           int type = getItemViewType(position);
            switch (type){
                case 0:
                    HeaderHolder hHolder = null;
                    if (convertView == null) {
                        convertView = View.inflate(getApplicationContext(),
                                R.layout.list_item_header, null);
                        hHolder = new HeaderHolder();
                        hHolder.tvHeader = (TextView) convertView
                                .findViewById(R.id.tv_header);
                        convertView.setTag(hHolder);
                    } else {
                        hHolder = (HeaderHolder) convertView.getTag();
                    }

                    if (position == 0) {
                        hHolder.tvHeader.setText("用户应用(" + mUserList.size() + ")");
                    } else {
                        hHolder.tvHeader
                                .setText("系统应用(" + mSystemList.size() + ")");
                    }
                    break;
                case 1:
                    ViewHolder holder = null;
                    if(convertView == null){
                        convertView = View.inflate(getApplicationContext(),R.layout.list_item_appinfo,null);
                        holder = new ViewHolder();
                        holder.tvName = (TextView) convertView.findViewById(R.id.tv_app_name);
                        holder.tvLocation = (TextView) convertView.findViewById(R.id.tv_location);
                        holder.ivIcon = (ImageView) convertView.findViewById(R.id.iv_icon);
                        convertView.setTag(holder);
                    }else {
                        holder = (ViewHolder) convertView.getTag();
                    }
                    AppInfo info = getItem(position);
                    holder.tvName.setText(info.name);
                    holder.ivIcon.setImageDrawable(info.icon);
                    if(info.isRom){
                        holder.tvLocation.setText("手机内存");
                    }else {
                        holder.tvLocation.setText("外置储存卡");
                    }
                    break;
            }
            return convertView;
        }
    }
    static class ViewHolder {
        public TextView tvName;
        public TextView tvLocation;
        public ImageView ivIcon;
    }
    static class HeaderHolder {
        public TextView tvHeader;
    }
    @Override
    public void onClick(View v) {

        mPopupWindow.dismiss();// 弹窗消失

        switch (v.getId()) {
            case R.id.tv_uninstall:
                System.out.println("卸载:" + mCurrentAppInfo.name);
                uninstall();
                break;
            case R.id.tv_launch:
                System.out.println("启动");
                launch();
                break;
            case R.id.tv_share:
                System.out.println("分享");
                 share();
                break;

            default:
                break;
        }
    }
    /**
     * 分享 - 调用系统所有可以分享的app列表,选择app进行分享
     */
    private void share() {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");// 分享纯文本
        intent.putExtra(Intent.EXTRA_TEXT,
                "分享给你一个很好的应用哦,下载地址:https://play.google.com/store/apps/details?id="
                        + mCurrentAppInfo.packageName);
        startActivity(intent);
    }

    /**
     * 启动
     */
    private void launch() {
        PackageManager pm = getPackageManager();
        Intent intent = pm
                .getLaunchIntentForPackage(mCurrentAppInfo.packageName);// 启动页面的Intent
        if (intent != null) {
            startActivity(intent);
        } else {
            Toast.makeText(getApplicationContext(),"找不到启动页面!",Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 卸载
     */
    private void uninstall() {
        if (mCurrentAppInfo.isUser) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_DELETE);
            intent.setData(Uri.parse("package:" + mCurrentAppInfo.packageName));
            startActivityForResult(intent, 0);
        } else {
            Toast.makeText(getApplicationContext(),"需要ROOT权限！!",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 卸载完成后重新加载数据
        initAppData();
    }
}
